package cn.mymall.web.controller.houtai.mall;

import cn.mymall.entity.mall.Vendor;
import cn.mymall.service.mall.IVendorService;
import cn.mymall.support.ResultCode;
import cn.mymall.util.BaseWebUtil;
import cn.mymall.util.BindUtils;
import cn.mymall.web.controller.houtai.BaseHoutaiController;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class VendorApiController extends BaseHoutaiController {
	@Autowired
	private IVendorService vendorService;

	// 列表
	@RequestMapping("/api/vendor/list")
	public ResultCode list(Integer pagenum, Integer pagesize, String vendorName, String isAll) {
		if(pagenum==null){
			pagenum = 1;
		}
		if(pagesize==null){
			pagesize = 10;
		}
		if(StringUtils.equalsIgnoreCase(isAll, "Y")){
			pagesize = 100;
		}
		QueryWrapper<Vendor> ew = new QueryWrapper<>();
		if(StringUtils.isNotBlank(vendorName)){
			ew.like("vendor_name", vendorName);
		}

		ew.orderByDesc("id");
		Page pageParams = new Page(pagenum,pagesize);
		Page<Vendor> page = vendorService.page(pageParams,ew);
		List<Vendor> list = page.getRecords();
		Map map = new HashMap<>();
		map.put("vendorList", list);
		map.put("page", ImmutableMap.of("total", page.getTotal(), "pagenum", page.getCurrent()));
		return ResultCode.getSuccessReturn(map);
	}

	// 新增or修改
	@RequestMapping("/api/vendor/get")
	public ResultCode modifyCategory(Integer id) {
		Vendor vendor = new Vendor();
		if (id != null) {
			vendor = vendorService.getById(id);
		}
		return ResultCode.getSuccessReturn(vendor);
	}

	// 保存
	@RequestMapping("/api/vendor/save")
	public ResultCode<Vendor> saveCategory(Integer id) {
		Vendor vendor = null;
		if (id != null) {
			vendor = vendorService.getById(id);
		} else {
			vendor = new Vendor();
		}
		BindUtils.bindData(vendor, BaseWebUtil.getRequestParams());
		if(StringUtils.isBlank(vendor.getVendorName())) {
			return ResultCode.getFailure("请输入名称");
		}
		vendorService.saveOrUpdate(vendor);
		return ResultCode.SUCCESS;
	}
}
